<?php

namespace App\Services;
use Workerman\Timer; // 只能在onXXXX回调中添加定时器。全局的定时器推荐在onWorkerStart回调中设置，针对某个连接的定时器推荐在onConnect中设置。
use Illuminate\Support\Facades\Redis;


class JieShunService extends HttpClientService
{
    public $userName, $password, $keyUrl, $appId, $key, $timestamp, $sign, $httpQueue, $headers;

    public function __construct()
    {
        $this->httpQueue = env("WORKERMAN_REDIS_HTTP");
        $this->userName = env('JIESHUN_USERNAME');
        $this->password = env('JIESHUN_PASSWORD');
        $this->keyUrl = 'http://192.168.1.30:9071/internal/sign'; // 获取签名url
        //$this->getKey(); // 获取$appId 以及key属性
        //$this->getSign(); // 初次获取签名及请求头
//        Timer::add(5, function() { // 设置一个定时器，每隔240秒重新获取签名
//            $this->getSign();
//        });

    }

    /**
     * @param $keyUrl url
     * @return void
     */
    protected function getKey()
    {
        if (empty($this->key)) {
            $res = $this->post($this->keyUrl, ['userName' => $this->userName, 'password' => $this->password]);
            if (!empty($res)) {
                $this->key = $res['data'][0]['key'];
                $this->appId = $res['data'][0]['appId'];
            }
        }
    }

    /**
     * @return void 获取签名及请求头
     */
    protected function getSign()
    {
        $this->timestamp = time();
        $random = 'random';
        $str = "random" . $random . "timestamp" . $this->timestamp . "key" . $this->key;
        $this->sign = strtoupper(md5($str)); // 获得签名
        if (empty($this->headers)) {
            $this->headers = [];
        }
        $this->headers['appId'] = $this->appId;
        $this->headers['v'] = 1.0;
        $this->headers['random'] = 'random'; // random 为random
        $this->headers['timestamp'] = $this->timestamp; // 获取当前签名用的时间戳
        $this->headers['sign'] = $this->sign;
    }

    public function test()
    {
        $res = $this->post('http://192.168.1.30:9071/base/devices', ['userName' => $this->userName, 'password' => $this->password], $this->headers);
        //var_dump($this->headers);
        //var_dump($res);
    }

}

